//
//  URLConnection.m
//  e-nurse
//
//  Created by  on 4/11/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "URLConnection.h"
#import "FileUtils.h"

size_t writeDataCallback(void *buffer, size_t size, size_t nmemb, void *userp);

@interface URLConnection () {
@private
    BOOL isFinished;
}

@property (strong, nonatomic) NSURLConnection *connection;
@property (strong, nonatomic) NSFileHandle *fileHandle;
@property (strong, nonatomic) NSString *filePath;
@end


@implementation URLConnection
@synthesize connection = _connection;
@synthesize fileHandle = _fileHandle;
@synthesize filePath = _filePath;

+ (double)networkTimeout
{
    return [(NSNumber*)[[[NSBundle mainBundle] infoDictionary] objectForKey:@"NetworkTimeout"] doubleValue];
}

+ (NSString*)createParameterString:(NSDictionary*)parameters
{
    NSString *result = nil;
    for (NSString * theKey in parameters) 
    {
        NSString *theValue = [[parameters objectForKey:theKey] retain];
        if(result != nil)
        {
            NSString *temp = result;
            
            result = [[NSString alloc] initWithFormat:@"?%@&%@=%@", result, theKey, theValue];
            
            [temp release];
        }
        else
        {
            result = [[NSString alloc] initWithFormat:@"%@=%@", theKey, theValue];
        }
    }
    return [result autorelease];
}

+ (NSString*)createServerUrl:(NSString*)address path:(NSString*)path
{
    NSString *result = [[[NSString alloc] initWithFormat:@"http://%@/VisionService%@", address, path] autorelease];
    result = [result stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
    
    result = [result stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    return result;
}

- (void)dealloc
{
    self.connection = nil;
    self.fileHandle = nil;
    self.filePath = nil;
    
    [super dealloc];
}

+ (NSString*)postRequestSync:(NSString*)url parameters:(NSString*)params headers:(NSDictionary*)headers body:(NSData*)body
{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];           
    [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", url]]]; 
    [request setTimeoutInterval:[URLConnection networkTimeout]];
    
    for (NSString* theKey in headers)
    {
        NSString *theValue = [headers objectForKey:theKey];
        [request addValue:theValue forHTTPHeaderField:theKey];
    }
    
    [request setHTTPMethod:@"POST"];    
    [request setHTTPBody:body];
    
    NSHTTPURLResponse *response;
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    [request release];
    
    NSString *result = [[[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding] autorelease];
    NSLog(@"HTTP Response: %@\n", result);
    if(response.statusCode == 200)
    {
       return result;
    }
    else 
    {
        return @"";
    }
}

+ (NSString*)getRequestSync:(NSString*)url headers:(NSDictionary*)headers
{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];           
    [request setURL:[NSURL URLWithString:url]];
    [request setTimeoutInterval:[URLConnection networkTimeout]];

    for (NSString* theKey in headers)
    {
        NSString *theValue = [headers objectForKey:theKey];
        [request addValue:theValue forHTTPHeaderField:theKey];
    }
    
    [request setHTTPMethod:@"GET"];  

    NSHTTPURLResponse *response;
    NSError *error;
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request   
                                               returningResponse:&response error:&error];
    NSLog(@"%@", response.description);
    [request release]; 
    
    NSString *result = [[[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding] autorelease];
    NSLog(@"HTTP Response: %@\n", result);
    if(response.statusCode == 200)
    {
        return result;
    }
    else 
    {
        return @"";
    }
}

- (void)downloadFile:(NSString*)url filePath:(NSString*)filePath headers:(NSDictionary*)headers
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if([fileManager fileExistsAtPath:filePath])
        return;
    
    if(![FileUtils directoryExists:[filePath stringByDeletingLastPathComponent]])
    {
        [fileManager createDirectoryAtPath:[filePath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];        
    }
    [fileManager createFileAtPath:filePath contents:nil attributes:nil];
    self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];

    isFinished = false;
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    self.connection = connection;
    [connection release];
    
    while (!isFinished) 
    {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    }
}
 
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.fileHandle seekToEndOfFile];
    [self.fileHandle writeData:data];
}

- (void)showAlertView:(NSString*)message title:(NSString*)title
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
    [alertView release];    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [self.fileHandle closeFile];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if([fileManager fileExistsAtPath:self.filePath])
    {
        [fileManager removeItemAtPath:self.filePath error:nil];
    }
    
    [self showAlertView:[error localizedDescription] title:@"连接错误"];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [self.fileHandle closeFile];
    
    isFinished = true;
}

@end
